package spring.my.db.sharding.demo.config.db.druid;

import com.alibaba.druid.pool.DruidDataSource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.context.annotation.PropertySource;

import javax.sql.DataSource;

/**
 * druid 连接池配置
 * <p>
 * 喜欢的话也可以使用 springboot 新的方式注入方式
 *
 * @Bean
 * @ConfigurationProperties("spring.datasource.druid." ) 注意配置的前缀保持一致且满足要求
 */
@Configuration
@PropertySource("classpath:datasource.properties")
public class DruidDBConfig {

    private Logger logger = LoggerFactory.getLogger(DruidDBConfig.class);

    @Value("${spring.datasource.master.url}")
    private String dbUrl;

    @Value("${spring.datasource.master.username}")
    private String username;

    @Value("${spring.datasource.master.password}")
    private String password;

    @Value("${spring.datasource.master.driverClassName}")
    private String driverClassName;


    @Bean("masterDataSource")     //声明其为Bean实例
    @Primary  //在同样的DataSource中，首先使用被标注的DataSource
    @Autowired
    public DataSource dataSource(DruidDataSource druidDatasource) throws CloneNotSupportedException {
        DruidDataSource dataSource = (DruidDataSource) druidDatasource.clone();
        String blankString = "";
        if (!blankString.equals(dbUrl) && !blankString.equals(username) && !blankString.equals(password) && !blankString.equals(driverClassName)) {
            // 数据库地址
            dataSource.setUrl(this.dbUrl);
            // 连接用户名
            dataSource.setUsername(username);
            // 连接密码
            dataSource.setPassword(password);
            // mysql驱动
            dataSource.setDriverClassName(driverClassName);
        }
        return dataSource;
    }
}
